package com.yinuo.starter.dao;

import com.yinuo.starter.bean.TransactionalBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class TransactionalDaoImpl implements TransactionalDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final String INSERT_SQL = "insert into `%TRANS%_DATA` (id, topic_name, tag_name, `keys`, `value`, `type`" +
            ", create_time, modify_time) values (?, ?, ?, ?, ?, ?, ?, ?)";

    private final String DELETE_SQL = "delete from `%TRANS%_DATA` where id = ? and `type` = ?";

    private final String SELECT_SQL = "select id, topic_name, tag_name, `keys`, `value`, `type`, create_time, modify_time from" +
            " `%TRANS%_DATA` where id = ? and `type` = ? limit 1";



    @Override
    public int insert(TransactionalBean transactionalBean) {
        return jdbcTemplate.update(INSERT_SQL, preparedStatement -> {
            preparedStatement.setString(1, transactionalBean.getId());
            preparedStatement.setString(2, transactionalBean.getTopicName());
            preparedStatement.setString(3, transactionalBean.getTagName());
            preparedStatement.setString(4, transactionalBean.getKeys());
            preparedStatement.setString(5, transactionalBean.getValue());
            preparedStatement.setInt(6, transactionalBean.getType());
            preparedStatement.setTimestamp(7, transactionalBean.getCreateTime());
            preparedStatement.setTimestamp(8, transactionalBean.getModifyTime());
        });
    }

    @Override
    public TransactionalBean selectByPrimary(String id, Integer type) {
        List<TransactionalBean> list = jdbcTemplate.query(SELECT_SQL
                , new Object[]{id, type}, new BeanPropertyRowMapper<>(TransactionalBean.class));
        if(list != null && list.size() > 0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public int deleteByPrimary(String id, Integer type) {
        return jdbcTemplate.update(DELETE_SQL, preparedStatement -> {
            preparedStatement.setString(1, id);
            preparedStatement.setInt(2, type);
        });
    }

}
